package com.sun.module_base.network.https


import android.util.Log
import com.sun.module_base.app.BaseApp
import java.io.IOException
import java.io.InputStream
import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.CertificateFactory
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManagerFactory

/**
 *@author:sunc
 *@time :2025/7/21 11:19
 *@desc: 描述
 * jks 转 bks
 */
object SslContextFactory {
    private const val CLIENT_AGREEMENT = "TLS" //使用协议

    private const val TRUSTSTORE_PUB_KEY = "sun.bks"
    private const val CLIENT_TRUST_MANAGER = "X.509"
    private const val CLIENT_TRUST_KEYSTORE = "BKS"
    private const val CLIENT_TRUST_KEY = "PKCS12"
    private const val CLIENT_TRUST_PROVIDER = "BC"
    private const val CLIENT_TRUST_PWD = "123456"
    private const val SELF_CERT_PWD = "123456"

    /**
     * 单项认证
     */
    fun getSSLSocketFactoryForOneWay(): SSLSocketFactory? {
        try {
            val certificate = BaseApp.INSTANCE.assets.open(TRUSTSTORE_PUB_KEY)
            val keyStore = KeyStore.getInstance(CLIENT_TRUST_KEYSTORE)
            keyStore.load(certificate, CLIENT_TRUST_PWD.toCharArray())
            try {
                certificate.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            val sslContext = SSLContext.getInstance(CLIENT_AGREEMENT)
            val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(keyStore)
            sslContext.init(
                null,
                trustManagerFactory.trustManagers,
                SecureRandom()
            )
            return sslContext.socketFactory
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Log.d("hello", ": SSLSocketFactory is null")
        return null
    }

    /**
     * 单项认证
     */
    fun getSSLSocketFactoryForOneWay(vararg certificates: InputStream?): SSLSocketFactory? {
        try {
            val certificateFactory =
                CertificateFactory.getInstance(
                    CLIENT_TRUST_MANAGER,
                    CLIENT_TRUST_PROVIDER
                )
            val keyStore =
                KeyStore.getInstance(CLIENT_TRUST_KEYSTORE)
            keyStore.load(null)
            var index = 0
            for (certificate in certificates) {
                val certificateAlias = Integer.toString(index++)
                keyStore.setCertificateEntry(
                    certificateAlias,
                    certificateFactory.generateCertificate(certificate)
                )
                try {
                    certificate?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            val sslContext =
                SSLContext.getInstance(CLIENT_AGREEMENT)
            val trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(keyStore)
            sslContext.init(
                null,
                trustManagerFactory.trustManagers,
                SecureRandom()
            )
            return sslContext.socketFactory
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 双向认证
     *
     * @return SSLSocketFactory
     */
    fun getSSLSocketFactoryForTwoWay(): SSLSocketFactory? {
        try {
            // 私钥
            val certificate: InputStream = BaseApp.INSTANCE.assets.open(TRUSTSTORE_PUB_KEY)
            val keyStore = KeyStore.getInstance(CLIENT_TRUST_KEY)
            keyStore.load(certificate, SELF_CERT_PWD.toCharArray())
            val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
            kmf.init(keyStore, SELF_CERT_PWD.toCharArray())
            try {
                certificate.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }

            //初始化keystore
            val clientKeyStore =
                KeyStore.getInstance(CLIENT_TRUST_KEYSTORE)
            clientKeyStore.load(
                // 公钥
                BaseApp.INSTANCE.assets.open(TRUSTSTORE_PUB_KEY),
                CLIENT_TRUST_PWD.toCharArray()
            )
            val sslContext =
                SSLContext.getInstance(CLIENT_AGREEMENT)
            val trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(clientKeyStore)
            val keyManagerFactory =
                KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
            keyManagerFactory.init(
                clientKeyStore,
                SELF_CERT_PWD.toCharArray()
            )
            sslContext.init(
                kmf.keyManagers,
                trustManagerFactory.trustManagers,
                SecureRandom()
            )
            return sslContext.socketFactory
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}